const { OPERATION_IS_NOT_ALLOWED } = require("../config/error");
const permissionService = require("../service/permission.service");

/* const verifyPermission = async (ctx, next) => {
  const { momentId } = ctx.request.body;
  const { id } = ctx.user;

  const isPermission = await permissionService.checkMoment(momentId, id);
  // Boolean(result.length);

  if (!isPermission) {
    return ctx.app.emit("error", OPERATION_IS_NOT_ALLOWED, ctx);
  }

  await next();
};
 */

// 方式一 ： 返回一个中间件

/* const verifyPermission = function (resouce) {

  return async (ctx, next) => {
    const { momentId } = ctx.request.body;
    const { id } = ctx.user;

    const isPermission = await permissionService.checkMoment(momentId, id);
    // Boolean(result.length);

    if (!isPermission) {
      return ctx.app.emit("error", OPERATION_IS_NOT_ALLOWED, ctx);
    }

    await next();
  };
};

 */

const verifyPermission = async (ctx, next) => {
  const { momentId } = ctx.request.body;

  /* 
    * 动态获取表的名字 需要命名规范
  */
  // console.log(Object.keys(ctx.request.body));

  // console.log(
  //   Object.keys(ctx.request.body)
  //     .find((item) => item.endsWith("Id"))
  //     .replace("Id", "")
  // );

  const { id } = ctx.user;

  const isPermission = await permissionService.checkMoment(momentId, id);
  // Boolean(result.length);

  if (!isPermission) {
    return ctx.app.emit("error", OPERATION_IS_NOT_ALLOWED, ctx);
  }

  await next();
};

module.exports = {
  verifyPermission,
};
